#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>


#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>

#include<list>

#include<cmath>


#include <iomanip>

#include <iostream>     // std::cout
#include <algorithm>    // std::for_each
#include <vector>       // std::vector
#include <stack>
#include <regex>
#include <sstream>

using namespace std;


// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "10015"

std::string bytes_to_hexstr(unsigned char* first, unsigned char* last)
{
    std::ostringstream oss;
    oss << std::hex << std::setfill('0');
    while(first<last) oss << std::setw(2) << int(*first++);
    return oss.str();
}

/* utility function to convert hex character representation to their nibble (4 bit) values */
static unsigned char nibbleFromChar(char c)
{
	if(c >= '0' && c <= '9') return c - '0';
	if(c >= 'a' && c <= 'f') return c - 'a' + 10;
	if(c >= 'A' && c <= 'F') return c - 'A' + 10;
	return 255;
}

/* Convert a string of characters representing a hex buffer into a series of bytes of that real value */
void hexStringToBytes(const char *inhex, unsigned char *ucOut)
{	
	unsigned char *p;
	int len, i;	
    len = strlen(inhex) / 2;	
	for(i=0, p = (unsigned char *) inhex; i<len; i++) {
		ucOut[i] = (nibbleFromChar(*p) << 4) | nibbleFromChar(*(p+1));
		p += 2;
	}
	return;
}

int __cdecl main(void) 
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;
    
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket
    closesocket(ListenSocket);

    std::string datas[] = {
"7e427d5e000b532400000a000000",
"3401e000000d00000101a001aa15d3010136040a01001400a0018f01b90080c17e",
"7e427d5e000b532400",
"000a0000003401e000000d00000101a001aa15d3010137040a01001400a0018f01b900e3847e",
"7e427d5e0003530f",
"00000000000003e124020a00fdffdac03e7e",
"7e427d5e000b",
"532400000a0000003401e000000d00000101a101aa15d3010138040a01001400a1018f01b900a2357e",
"7e427d5e0003531d00000a00000003c1240101003c000000",
"07004500285704000000d0000070fb7e",
"7e427d5e0003531d00000000000003",
"e12401030006000e0000000000205704007d5e0000000051507e",
"7e427d5e000b53240000",
"0a0000003401e000000d00000101a001ab1ad3010139040a01001400a0018f01b9005d057e",
"7e427d5e000b532400000a0000003401e000000d00000101a001ab",
"17d301013a040a01001400a0018f01b900821e7e",
"7e427d5e0003530f00000000000003e124",
"020a00fdffdac03e7e",
"7e427d5e000b532400",
"000a0000003401e000000d00000101a001aa1dd301013b040a01001400a0018f01b900040d7e",
"7e427d5e000b532400000a0000003401e000"};
    // Receive until the peer shuts down the connection
    for (int i = 0; i < sizeof(datas) / sizeof(datas[0]); i++) 
    {
        printf("data is: %s len=%d\n", datas[i].c_str(), datas[i].length());
        ZeroMemory(recvbuf, sizeof(recvbuf));
 
        // Echo the buffer back to the sender
        char senddata[]={0x7E, 0x42, 0x7D, 0x5E, 0x00, 0x0B, 0x53, 0x24, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x34, 0x01, 0xE0, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x01, 0x01, 0xA1, 0x01, 0xAF, 0x55, 0x25, 0x02, 0x02, 0x42, 0x05, 0x0A, 0x02, 0x00, 0x14, 0x00, 0xA1, 0x01, 0x00, 0x00, 0x0C, 0x00, 0x8D, 0x43, 0x7E};
        unsigned char data[100] = {0};
        hexStringToBytes(datas[i].c_str(), data);
        //std::cout << bytes_to_hexstr(data, data + datas[i].length() / 2) << std::endl;
        iSendResult = send( ClientSocket, (char *)data, datas[i].length() / 2, 0 );
        if (iSendResult == SOCKET_ERROR) {
            printf("send failed with error: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }
        printf("Bytes sent: %d\n", iSendResult);
        Sleep(1000);

    }

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;
}